<?php
namespace app\middleware\admin;

use app\model\AuthGroup;
use app\model\AuthRule;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class AuthRuleCheck implements MiddlewareInterface
{
    public function process(Request $request, callable $handler) : Response
    {
    	$controller = $request->controller;
    	$ignore = ['app\admin\controller\AuthController'];

        if(!in_array($controller, $ignore))
        {
            $action = $request->path();  //操作的方法名称
            $session = $request->session();
            $admin_info = $session->get('admin_info');

            //获取权限集合
            $auth_group = AuthGroup::where('id', $admin_info['group_id'])->where('status',1)->value('rules');
            if(empty($auth_group))
            {
                if($request->method() == 'GET')
                {
                    return view('admin/no_auth');
                }else{
                    return returnJson(403, '您没有此权限!');
                }
            }
            if($auth_group != '*')
            {
                $auth_group_route = AuthRule::whereIn('id', $auth_group)->where('status',1)->column('route');
                $auth_group_route = array_values(array_filter($auth_group_route));
                if(!in_array($action, $auth_group_route))
                {
                    if($request->method() == 'GET')
                    {
                        return view('admin/no_auth');
                    }else{
                        return returnJson(403, '您没有此权限!');
                    }
                }
            }
        }
        return $handler($request);
    }
}